// 获取用户
var config = require("../../util/dbconfig");
const { generate, verify } = require("../../util/jwt");

// 获取随机数
function rand(min, max) {
  return Math.floor(Math.random() * (max - min)) + min;
}
validatePhoneCode = [];
let sendCodeP = (phone) => {
  for (var item of validatePhoneCode) {
    if (phone == item.phone) {
      return true;
    }
  }
  return false;
};
let findCodeAndPhone = (phone, code) => {
  for (var item of validatePhoneCode) {
    if (phone == item.phone && code == item.code) {
      return "login";
    }
  }
  return "error";
};
// 模拟验证码发送
sendCode = (req, res) => {
  let phone = req.query.phone;
  let code = rand(1000, 9999);
  if (sendCodeP(phone)) {
    res.send({
      code: 400,
      message: "已经发送过验证码，请稍后再发",
    });
  }
  validatePhoneCode.push({
    phone: phone,
    code: code,
  });
  console.log(validatePhoneCode);
  res.send({
    code: 200,
    message: "发送成功",
  });
  console.log(code);
};
// 验证码登录
codePhoneLogin = (req, res) => {
  let { phone, code } = req.query;
  // 该手机号是否发送过验证码
  if (sendCodeP(phone)) {
    let status = findCodeAndPhone(phone, code);
    if (status == "login") {
      // 登录成功
      // 登录成功之后操作
      res.send({
        code: 200,
        message: "登录成功",
      });
    } else if (status == "error") {
      res.send({
        code: 200,
        message: "登录失败",
      });
    }
  } else {
    res.send({
      code: 400,
      message: "未发送验证码",
    });
  }
};
login = (req, res) => {
  let obj = req.body;
  // 1-查询数据
  const sqlStr = "select * from users where username=?";
  config.sqlConnect(sqlStr, obj.username, (err, result) => {
    // 查询失败
    if (err)
      return res.send({
        code: 500,
        message: "用户不存在或密码错误",
      });
    // 查询成功
    if (result.length === 0)
      return res.send({
        code: 500,
        message: "用户不存在或密码错误",
      });
    const user = result[0];
    // 2-校验密码
    const isMatch = obj.password == user.password;
    if (!isMatch)
      return res.send({
        code: 500,
        message: "用户不存在或密码错误",
      });
    // 3-登录成功
    const token = generate({ id: user.id });
    res.send({
      code: 200,
      message: "登录成功",
      data: token,
    });
  });
};
getUserInfo = (req, res) => {
  let userId = verify(req.headers.authorization).id;
  const sqlStr = "select * from users where id=?";
  config.sqlConnect(sqlStr, userId, (err, result) => {
    // 查询失败
    if (err)
      return res.send({
        code: 500,
        message: "用户不存在或密码错误",
      });
    // 查询成功
    console.log(result[0]);
    let data = {
      username: result[0].username,
      role: result[0].role,
      avatar: result[0].avatar,
      introduction: result[0].introduction,
      gender: result[0].gender,
      id: result[0].id,
    };
    res.send({
      code: 200,
      data: data,
    });
  });
};
updateUserInfo = (req, res) => {
  const user = req.body;
  const userId = verify(req.headers.authorization).id;
  const sqlStr = `update users set username='${user.username}', avatar=${user.avatar}, gender=${user.gender},introduction='${user.introduction}' where id=?`;
  config.sqlConnect(sqlStr, userId, (err, result) => {
    console.log(err);
    if (err)
      return res.send({
        code: 500,
        message: "修改失败",
      });
    // 查询成功

    res.send({
      code: 200,
      message: "修改成功",
    });
  });
};
getList = (req, res) => {
  if (req.query.startDate !== undefined) {
    const startDate = req.query.startDate;
    const endDate = req.query.endDate;
    console.log(startDate, endDate);
    var totalSql = `SELECT COUNT(*) AS total FROM list WHERE date BETWEEN '${startDate}' AND '${endDate}'`;
    config.sqlConnect(totalSql, "", (err, result) => {
      console.log(result);
      const total = result[0].total;
      let pageSize = req.query.pageSize;
      let pageNum = req.query.currentPage;
      const startIndex = (pageNum - 1) * pageSize;
      var sql = `SELECT * FROM list WHERE date BETWEEN '${startDate}' AND '${endDate}' LIMIT ${startIndex}, ${pageSize}`;
      var sqlArr = [];
      var callBack = (err, result) => {
        if (err) {
          res.send({
            code: 500,
            message: "查询失败",
          });
        } else {
          res.send({
            code: 200,
            message: "成功",
            data: result,
            total: total,
          });
        }
      };
      config.sqlConnect(sql, sqlArr, callBack);
    });
  } else {
    var totalSql = "SELECT COUNT(*) AS total FROM list";
    config.sqlConnect(totalSql, "", (err, result) => {
      const total = result[0].total;
      let pageSize = req.query.pageSize;
      let pageNum = req.query.currentPage;
      const startIndex = (pageNum - 1) * pageSize;
      var sql = `SELECT * FROM list LIMIT ${startIndex}, ${pageSize} `;
      var sqlArr = [];
      var callBack = (err, result) => {
        if (err) {
          res.send({
            code: 500,
            message: "查询失败",
          });
        } else {
          res.send({
            code: 200,
            message: "成功",
            data: result,
            total: total,
          });
        }
      };
      config.sqlConnect(sql, sqlArr, callBack);
    });
  }
};
module.exports = {
  sendCode,
  codePhoneLogin,
  login,
  getUserInfo,
  updateUserInfo,
  getList,
};
